package com.gdyx.app.web.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gdyx.app.web.annotation.Authorisation;
import com.gdyx.app.web.dto.ZTreeNode;
import com.gdyx.app.web.model.*;
import com.gdyx.app.web.svc.*;
import com.gdyx.app.web.util.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Y_Coffee on 2017/7/27.
 */
@Controller
@RequestMapping("/MpsDept")
@Scope("prototype")
public class MpsDeptController extends BaseController {
    @Autowired
    MpsDeptSvc mpsDeptSvc;
    @Autowired
    MpsRoleSvc mpsRoleSvc;
    @Autowired
    MpsDeptRoleSvc mpsDeptRoleSvc;
    @Autowired
    MpsOrgSvc mpsOrgSvc;
    @Autowired
    HttpServletRequest request;
    @Autowired
    MpsDeptUserSvc mpsDeptUserSvc;


    @Authorisation(value = "/MpsDept/goMpsDeptList")
    @GetMapping("/goMpsDeptList")
    public ModelAndView goMpsDeptList(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        List<MpsDept> list = mpsDeptSvc.findMpsDeptByOId(org_session);
        List<MpsDept> det  = new ArrayList<>();
        DoRootDept(list, det);
        view.addObject("MpsDeptList", det);
        view.addObject("respMsg", respMsg);
        view.setViewName("MpsDeptList");
        return view;
    }

    @Authorisation(value = "/MpsDept/Save")
    @GetMapping("goMpsDeptAdd")
    public ModelAndView goMpsDeptAdd(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        List<MpsRole>  mpsRoleList =mpsRoleSvc.findMpsRoleByOId(org_session);
        List<MpsDept>  mpsDeptList = mpsDeptSvc.findMpsDeptByOId(org_session);
        view.addObject("MpsDeptList", JSON.toJSONString(mpsDeptList));
        view.addObject("MpsRoleList", mpsRoleList);
        view.setViewName("MpsDeptAdd");
        return view;
    }

    @Authorisation(value = "/MpsDept/Update")
    @GetMapping("goMpsDeptEdit")
    public ModelAndView goMpsDeptEdit(@ModelAttribute("respMsg") String respMsg, @RequestParam("id") String id) {
        ModelAndView view = new ModelAndView();
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        MpsDept mpsDept = mpsDeptSvc.findMpsDeptById(id);
        List<MpsRole> mpsRoleList = mpsRoleSvc.findMpsRoleByOId(org_session);
        List<MpsDept> list = mpsDeptSvc.findMpsDeptByOId(org_session);
        //已有的角色
        List<MpsDeptRole> mpsDeptRoles = mpsDeptRoleSvc.findDeptRoleByDid(id);
        List<String> roles = new ArrayList<>();
        for (MpsDeptRole mpsDeptRole : mpsDeptRoles) {
            roles.add(mpsDeptRole.getRoleId());
        }
        String[] roleStrs = roles.toArray(new String[roles.size()]);
        view.addObject("roleEcho", roleStrs);
        //部门归属机构
        view.addObject("orgId", mpsDept.getOrgId());
        view.addObject("D_I", mpsDept);
        view.addObject("MpsDeptList", JSON.toJSONString(list));
        view.addObject("MpsRoleList", mpsRoleList);
        view.setViewName("MpsDeptEdit");
        return view;
    }

    @Authorisation(value = "/MpsDept/Save")
    @PostMapping("Save")
    public String save(RedirectAttributes attr, MpsDept o) {
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "name", "=", o.getName(), "S"));
        map.put("conditions", conditions);
        int count = mpsDeptSvc.count(map);
        if (count > 0 || StringUtils.isEmpty(o.getName())) {
            attr.addFlashAttribute("respMsg", "操作失败，部门名称不能为空或已存在");
            return "redirect:/MpsDept/goMpsDeptAdd";
        }
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        o.setOrgId(org_session);
        mpsDeptSvc.save(o, mpsUser.getId());
        attr.addFlashAttribute("respMsg", "增加部门" + o.getName() + "成功");
        return "redirect:/MpsDept/goMpsDeptList";
    }

    @Authorisation(value = "/MpsDept/Delete")
    @GetMapping("Delete")
    public String Delete(RedirectAttributes attr, String id) {
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "parent", "=", id, "S"));
        map.put("conditions", conditions);
        int count = mpsDeptSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作失败，有子节点");
        } else {
            mpsDeptSvc.delete(id);
            attr.addFlashAttribute("respMsg", "删除部门成功");
        }
        return "redirect:/MpsDept/goMpsDeptList";
    }

    @Authorisation(value = "/MpsDept/Update")
    @PostMapping("Update")
    public String Update(RedirectAttributes attr, MpsDept o) {
        if (StringUtils.isEmpty(o.getName())) {
            attr.addFlashAttribute("respMsg", "操作失败，部门名称不能为空");
            return "redirect:/MpsDept/goMpsDeptEdit?id=" + o.getId();
        }
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "id", "<>", o.getId(), "S"));
        conditions.add(ruleBuild("and", "name", "=", o.getName(), "S"));
        map.put("conditions", conditions);
        int count = mpsDeptSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作失败，部门名称已存在");
            return "redirect:/MpsDept/goMpsDeptEdit?id=" + o.getId();
        }
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        o.setOrgId(org_session);
        mpsDeptSvc.update(o, mpsUser.getId());
        attr.addFlashAttribute("respMsg", "更新部门：" + o.getName() + "成功");
        return "redirect:/MpsDept/goMpsDeptList";
    }


    @GetMapping("AjaxMpsDept")
    @ResponseBody
    public String AjaxMpsFun() {
        List<MpsDept> list = mpsDeptSvc.findMpsDepts(new HashMap<>());
        JSONArray array = new JSONArray();
        List<MpsDept> det = new ArrayList<>();
        DoRootDept(list, det);
        det.stream().forEach(item -> {
            det.add(item);
        });
        return array.toString().replace("parent", "pId");
    }

    /**
     * 配置部门-回显数据
     * @param roleId
     * @return
     */
    @Authorisation(value = "/MpsDept/setRoleDept")
    @PostMapping("mpsAllDeptByRoleId")
    @ResponseBody
    public String mpsAllDeptByRoleId(@RequestParam("id") String roleId) {
        List<ZTreeNode> resultList = new ArrayList<>();
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        MpsUser nowMpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        //获取角色部门关联表-打勾
        List<MpsDeptRole> deptRoles = mpsDeptRoleSvc.findDeptRoleByRid(roleId);
        //获取当前机构的部门
        List<MpsDept> mpsDeptByOId = mpsDeptSvc.findMpsDeptByOId(org_session);
        for (MpsDept mpsDept : mpsDeptByOId) {
            ZTreeNode zTreeNode = new ZTreeNode();
            zTreeNode.setId(mpsDept.getId());
            zTreeNode.setpId(mpsDept.getParent());
            zTreeNode.setName(mpsDept.getName());
            zTreeNode.setOpen(true);
            for (MpsDeptRole deptRole : deptRoles) {
                if (mpsDept.getId().equals(deptRole.getDeptId())){
                    zTreeNode.setChecked(true);
                }
            }
            resultList.add(zTreeNode);
        }
        return JSONObject.toJSONString(resultList);
    }

    /**
     * 配置部门-保存部门
     * @param roleId
     * @param ids
     * @return
     */
    @Authorisation(value = "/MpsDept/setRoleDept")
    @PostMapping("setRoleDept")
    @ResponseBody
    public String setRoleDept(@RequestParam("roleId") String roleId, @RequestParam("ids") String ids) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        mpsDeptRoleSvc.setDept(ids, roleId, mpsUser.getId());
        return "{\"status\":\"success\"}";
    }
}
